package common

import (
	"go_gin_gorm_oceanlearn_study/model"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var jwtKey = []byte("a_secret_crect") //jwt加密的密钥

type Claims struct { //定义token的Claims
	UserId uint
	jwt.StandardClaims
}

//定义发放token的方法
func ReleaseToken(user model.User) (string, error)  {  
	expirationTime := time.Now().Add(7 * 24 * time.Hour)  //设置token 的过期时间为7天
	claims := &Claims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(), //token过期时间
			IssuedAt: time.Now().Unix(),  //token发放时间
			Issuer: "oceanlearn.tech", //谁发放的token
			Subject: "user token", //主题
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)  //使用jwt密钥生成token

	if err != nil {
		return "", err
	}

	return tokenString, nil
}

// {
//     "code": 200,
//     "data": {
//         "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjQsImV4cCI6MTY3ODY5NzIyNiwiaWF0IjoxNjc4MDkyNDI2LCJpc3MiOiJvY2VhbmxlYXJuLnRlY2giLCJzdWIiOiJ1c2VyIHRva2VuIn0.g_mgT8b_oNS1al6_76WLVLfWSj6SmacPy0Hz8CN-OsA"
//     },
//     "msg": "登陆成功"
// }

// 这里 token 由 三部分 组成：
//         "token":
//			"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.  // 协议头header，储存token使用的加密协议
//			eyJVc2VySWQiOjQsImV4cCI6MTY3ODY5NzIyNiwiaWF0IjoxNjc4MDkyNDI2LCJpc3MiOiJvY2VhbmxlYXJuLnRlY2giLCJzdWIiOiJ1c2VyIHRva2VuIn0. // 载荷
//			g_mgT8b_oNS1al6_76WLVLfWSj6SmacPy0Hz8CN-OsA" // 签证

//-----------------------------------------------------------------------------------------------------
// 使用 echo eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 | base64 -D 可以得到：{"alg":"HS256","typ":"JWT"}
// 使用 echo eyJVc2VySWQiOjQsImV4cCI6MTY3ODY5NzIyNiwiaWF0IjoxNjc4MDkyNDI2LCJpc3MiOiJvY2VhbmxlYXJuLnRlY2giLCJzdWIiOiJ1c2VyIHRva2VuIn0 | base64 -D
// 可以得到：{"UserId":3,"exp":15834180590,"iat":15828132590,"iss":"oceanlearn.tech","sub":"user token"}


// 从tokenString中解析出claims并返回
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	claims := &Claims{}

	token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})

	return token, claims, err
}